import json
import os
import re
from pathlib import Path
from dora import Node, DoraStatus
import pyarrow as pa
from mofa.kernel.utils.util import load_agent_config, load_dora_inputs_and_task, create_agent_output
from mofa.run.run_agent import run_dspy_or_crewai_agent
from mofa.utils.files.dir import get_relative_path
from mofa.utils.log.agent import record_agent_result_log

def read_file_to_string(file_path):
    with open(file_path, 'r') as file:
        return file.read()

def save_result_to_file(result, output_path):
    # 使用正则表达式提取 Rust 代码块
    rust_code_match = re.search(r'```rust\n(.*?)```', result, re.DOTALL)
    if rust_code_match:
        rust_code = rust_code_match.group(1).strip()
        with open(output_path, 'w') as file:
            file.write(rust_code)
    else:
        print("No Rust code found in the result.")


class Operator:
    def __init__(self):
        # 直接在这里指定 C 文件路径和输出路径
        self.c_file_path = "/home/mofaDora/zymmofa/mofa/python/examples/onlyreason/source/test.c"
        
        self.ir_file_path = "/home/mofaDora/zymmofa/mofa/python/examples/onlyreason/source/test.ll"

        self.output_path = "/home/mofaDora/zymmofa/mofa/python/examples/onlyreason/out/outfile/test.rs"
        self.task = "将C语言代码和对应的LLVM IR转换为Rust语言代码"
        


    def on_event(
        self,
        dora_event,
        send_output,
    ) -> DoraStatus:
        if dora_event["type"] == "INPUT":
            # 我们假设任何输入都会触发转换过程
            # 读取 C 文件内容
            c_code = read_file_to_string(self.c_file_path)
            ir_code = read_file_to_string(self.ir_file_path)
            #print(f"Read C code: {c_code[:100]}...")  # 打印前100个字符,确认读取成功
            
            self.task = "请将以下C代码和对应的LLVM IR转换为等效的Rust代码:\n\n" + c_code

            yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs', target_file_name='reasoner_agent.yml')
            
            inputs = load_agent_config(yaml_file_path)
            inputs["task"] = self.task
            inputs["c_code"] = c_code
            inputs["ir_code"] = ir_code
            
            print(f"Inputs to agent: {inputs}")

            agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
            
            # 提取 Rust 代码
            rust_code_match = re.search(r'```rust\n(.*?)```', agent_result, re.DOTALL)
            if rust_code_match:
                rust_code = rust_code_match.group(1).strip()
                save_result_to_file(rust_code, self.output_path)
                print(f'Extracted Rust code saved to: {self.output_path}')
                print('Rust code preview:')
                print(rust_code)
            else:
                print("No Rust code found in the result.")

            record_agent_result_log(agent_config=inputs,
                                    agent_result={
                                        "1, "+ inputs.get('log_step_name', "Step_one"): {self.task: agent_result}})
            
            save_result_to_file(agent_result, self.output_path)
            
            send_output("reasoner_results", pa.array([create_agent_output(step_name='code_conversion_results', output_data=agent_result, dataflow_status=os.getenv('IS_DATAFLOW_END',True))]), dora_event['metadata'])
            
            #print(f'Code conversion result saved to: {self.output_path}')
            print('Conversion result preview:', agent_result[:200] + '...' if len(agent_result) > 200 else agent_result)

        return DoraStatus.CONTINUE